<template>
  <div>
    <el-card>
      <el-button
        type="primary"
        icon="Plus"
        @click="addTrademark"
        v-has="`btn.Trademark.add`"
      >
        添加
      </el-button>
      <el-table :data="tableData" style="width: 100%" :border="true">
        <el-table-column
          type="index"
          label="序号"
          width="60"
          align="center"
          header-align="center"
        />
        <el-table-column prop="tmName" label="名称">
          <template #default="{ row }">
            <div>{{ row.tmName }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="logoUrl" label="logo">
          <template #default="{ row }">
            <img
              :src="row.logoUrl"
              alt="未有图片"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作"
          align="center"
          header-align="center"
        >
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateTrademark(row)"
            ></el-button>

            <el-popconfirm
              :title="`确定要删除${row.tmName}`"
              width="260px"
              icon="Delete"
              @confirm="removeTrademark(row)"
            >
              <template #reference>
                <el-button
                  type="primary"
                  size="small"
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 6, 9]"
        :background="background"
        layout=" prev, pager, next, jumper, ->, total, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="changePageNo"
      />
    </el-card>

    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改' : '添加'"
    >
      <el-form :model="trademarkParams" :rules="rules" ref="formRef">
        <el-form-item label="名称" :label-width="formLabelWidth" prop="tmName">
          <el-input v-model="trademarkParams.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="logo" :label-width="formLabelWidth" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark
} from '@/api/product/trademark'
import type {
  Records,
  TradeMarkResponseData,
  TradeMark
} from '@/api/product/trademark/type'
import type { FormInstance } from 'element-plus'

let tableData = ref<Records>([])
const pageNo = ref<number>(1)
const limit = ref<number>(10)
const total = ref<number>(0)

const background = ref(true)

const handleSizeChange = () => {
  pageNo.value = 1
  getHasTrademark()
}
const changePageNo = () => {
  getHasTrademark()
}

const getHasTrademark = async () => {
  const reqult: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value
  )
  tableData.value = reqult.data.records
  total.value = reqult.data.total
}

onMounted(() => {
  getHasTrademark()
})

const dialogFormVisible = ref<boolean>(false)
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: ''
})

type keys = keyof TradeMark

const addTrademark = () => {
  Object.keys(trademarkParams).forEach((key ) => {
    delete trademarkParams[key as keys]
  })
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''

  formRef.value?.clearValidate('tmName')
  formRef.value?.clearValidate('logoUrl')

  dialogFormVisible.value = true
}
const updateTrademark = (row: TradeMark) => {
  dialogFormVisible.value = true
  Object.assign(trademarkParams, row)

  formRef.value?.clearValidate('tmName')
  formRef.value?.clearValidate('logoUrl')
}
const removeTrademark = async (row: TradeMark) => {
  await reqDeleteTrademark(row.id as number)
  ElMessage.success('删除成功')
  !tableData.value.length && (pageNo.value -= 1)
  getHasTrademark()
}

const formLabelWidth = '80px'
const cancel = () => {
  dialogFormVisible.value = false
}
const confirm = async () => {
  try {
    await formRef.value?.validate()

    await reqAddOrUpdateTrademark(trademarkParams)
    ElMessage.success(trademarkParams.id ? '修改成功' : '添加成功')
    // 隐藏弹框
    dialogFormVisible.value = false
    // 刷新列表
    !trademarkParams.id && (pageNo.value = 1)
    getHasTrademark()
  } catch (error) {
    console.log(error)
  }
}

import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  trademarkParams.logoUrl = response.data

  formRef.value?.clearValidate('logoUrl')
}

const vlidatorTmName = (
  rule: any,
  value: string,
  callback: (error?: Error) => void
) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('名称至少输入两位'))
  }
}
const vlidatorLogoUrl = (
  rule: any,
  value: string,
  callback: (error?: Error) => void
) => {
  if (value) {
    callback()
  } else {
    callback(new Error('请上传图片'))
  }
}
const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: vlidatorTmName }],
  logoUrl: [{ required: true, trigger: 'change', validator: vlidatorLogoUrl }]
}
const formRef = ref<FormInstance>()
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
